﻿package net.wangit.adm.user;

import net.wangit.User;
import net.wangit.adm.group.GroupTreeFactory;
import net.wangit.context.LocalContext;
import net.wangit.user.AdminUser;
import net.wangit.user.UserFactory;
import net.wangit.user.admin.Admin;
import net.wangit.user.admin.AdminFactory;
import net.wangit.util.ArrayUtil;
import net.wangit.util.Checker;
import net.wangit.view.tree.Tree;

public class UserGroupTreeFactory extends GroupTreeFactory {

	private Admin administrator;
	private String groups[];

	public UserGroupTreeFactory() {
		administrator = null;
	}

	public Tree createTree(String treeDoamin) throws Exception {
		String userId = UserAuthUI.getAndSetUserId();
		if (Checker.isEmpty(userId))
			return null;
		User operator = LocalContext.getLocalContext().getActionContext()
				.getVisitor().getUser();
		if (operator instanceof AdminUser) {
			String administratorId = operator.get("adminid");
			administrator = AdminFactory.getAdmin(administratorId);
		}
		User user = UserFactory.getUser(userId);
		groups = user.getGroups();
		Tree tree = super.createTree(treeDoamin);
		tree.setAction((new StringBuilder(" (")).append(groups.length).append(
				"/").append(tree.size()).append(")").toString());
		return tree;
	}

	protected void setCustomAttribute(Tree tree, String groupId) {
		tree.setCheckValue(groupId);
		String checkbox;
		if (ArrayUtil.find(groups, groupId) >= 0)
			checkbox = "checked";
		else
			checkbox = "";
		if (administrator != null && !administrator.containsGroup(groupId))
			checkbox = (new StringBuilder(String.valueOf(checkbox))).append(
					" disabled").toString();
		tree.setCheckAttribute(checkbox);
	}

	protected void setName(Tree tree, String orgId, String orgName,
			int roleCount, int privilegeCount) {
		tree.setName((new StringBuilder(String.valueOf(roleCount))).append(" ")
				.append(orgName).append(" ").append(privilegeCount).toString());
	}
}
